﻿using System;
using System.Data;
using System.Globalization;
using BLL;
using ET;
using Ext.Net;
using Microsoft.Win32;

namespace ERP.Modules
{
    public partial class MCK_Connect : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        private static readonly MCK_BLL Mck = new MCK_BLL();
        public static zkemkeeper.CZKEMClass AxCzkem1 = new zkemkeeper.CZKEMClass();
        static int _iMachineNumber = 1;

        #region Connect Device
        protected void btnConnect_OnClick(object sender, EventArgs e)
        {
            int idwErrorCode = 0;
            if (AxCzkem1.Connect_Net(txtIP.Text, int.Parse(txtPort.Text)))
            {
                btnConnect.Hide();
                btnDisConect.Show();
                _iMachineNumber = 1;
                AxCzkem1.RegEvent(_iMachineNumber, 65535);
                HTML.clsFormat.Alert_INFO("", "Đã kết nối thiết bị");
            }
            else
            {
                AxCzkem1.GetLastError(ref idwErrorCode);
                HTML.clsFormat.Alert_ERROR("Lỗi", "Không thể kết nối với thiết bị, Mã lỗi = " + idwErrorCode);
            }
        }

        protected void btnDisConect_OnClick(object sender, DirectEventArgs e)
        {
            btnConnect.Show();
            btnDisConect.Hide();
            AxCzkem1.Disconnect();
            HTML.clsFormat.Alert_INFO("", "Hủy kết nối thiết bị");
        }

        protected void btnRsConnect_OnClick(object sender, DirectEventArgs e)
        {
            int idwErrorCode = 0;
            //accept serialport number from string like "COMi"
            int iPort;
            string sPort = cbPort.Text.Trim();
            for (iPort = 1; iPort < 10; iPort++)
            {
                if (sPort.IndexOf(iPort.ToString(), StringComparison.Ordinal) > -1)
                {
                    break;
                }
            }

            _iMachineNumber = Convert.ToInt32(txtMachineSN.Text.Trim());
            if (AxCzkem1.Connect_Com(iPort, _iMachineNumber, Convert.ToInt32(cbBaudRate.Text.Trim())))
            {
                AxCzkem1.RegEvent(_iMachineNumber, 65535);
            }
            else
            {
                AxCzkem1.GetLastError(ref idwErrorCode);
                HTML.clsFormat.Alert_ERROR("Lỗi", "Không thể kết nối với thiết bị, Mã lỗi = " + idwErrorCode);
            }
        }

        protected void btnRsDisConnect_OnClick(object sender, DirectEventArgs e)
        {
            btnRsConnect.Show();
            btnRsDisConnect.Hide();
            AxCzkem1.Disconnect();
            HTML.clsFormat.Alert_INFO("", "Hủy kết nối thiết bị");
        }

        protected void btnUSBConnect_OnClick(object sender, DirectEventArgs e)
        {
            int idwErrorCode = 0;
            string sCom = "";
            bool bSearch = SearchforCom(ref sCom);//modify by Darcy on Nov.26 2009
            if (bSearch == false)//modify by Darcy on Nov.26 2009
            {
                HTML.clsFormat.Alert_ERROR("Can not find the virtual serial port that can be used", "Error");
                return;
            }

            int iPort;
            for (iPort = 1; iPort < 10; iPort++)
            {
                if (sCom.IndexOf(iPort.ToString()) > -1)
                {
                    break;
                }
            }

            _iMachineNumber = Convert.ToInt32(txtMachineSN2.Text.Trim());
            if (_iMachineNumber == 0 || _iMachineNumber > 255)
            {
                HTML.clsFormat.Alert_ERROR("The Machine Number is invalid!", "Error");
                return;
            }

            const int iBaudRate = 115200; //115200 is one possible baudrate value(its value cannot be 0)

            if (AxCzkem1.Connect_Com(iPort, _iMachineNumber, iBaudRate))
            {
                AxCzkem1.RegEvent(_iMachineNumber, 65535);//Here you can register the realtime events that you want to be triggered(the parameters 65535 means registering all)
            }
            else
            {
                AxCzkem1.GetLastError(ref idwErrorCode);
                HTML.clsFormat.Alert_ERROR("Unable to connect the device,ErrorCode=" + idwErrorCode, "Error");
            }
        }

        protected void btnUSBDisConnec_OnClick(object sender, DirectEventArgs e)
        {
            btnUSBConnect.Show();
            btnUSBDisConnect.Hide();
            AxCzkem1.Disconnect();
            HTML.clsFormat.Alert_INFO("", "Hủy kết nối thiết bị");
        }
        public bool SearchforCom(ref string sCom)//modify by Darcy on Nov.26 2009
        {
            RegistryKey myReg = Registry.LocalMachine.OpenSubKey("HARDWARE\\DEVICEMAP\\SERIALCOMM");
            if (myReg != null)
            {
                string[] sComNames = myReg.GetValueNames();//strings array composed of the key name holded by the subkey "SERIALCOMM"
                for (int i = 0; i < sComNames.Length; i++)
                {
                    string sComValue = myReg.GetValue(sComNames[i]).ToString();
                    if (sComValue == "")
                    {
                        continue;
                    }

                    sCom = "";
                    if (sComNames[i] == "\\Device\\USBSER000")//find the virtual serial port created by usbclient
                    {
                        for (int j = 0; j <= 10; j++)
                        {
                            RegistryKey myReg2 = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Enum\USB\VID_1B55&PID_B400\" + j + @"\Device Parameters");//find the plug and play USB device
                            if (myReg2 != null)//add by Darcy on Nov.26 2009
                            {
                                string sTmpara = myReg2.GetValue("PortName").ToString();

                                if (sComValue == sTmpara)
                                {
                                    sCom = sTmpara;
                                    return true;//add by Darcy on Nov.26 2009
                                }
                            }
                        }
                    }
                }
            }
            return false;//add by Darcy on Nov.26 2009
        }
        #endregion

        public static DataTable getDataCheckLog()
        {
            var table = new DataTable();
            table.Columns.Add("IDMachineKeeper");
            table.Columns.Add("EnrollNumber");
            table.Columns.Add("VerifyMode");
            table.Columns.Add("InOutMode");
            table.Columns.Add("Date");
            table.Columns.Add("Workcode");

            AxCzkem1.EnableDevice(_iMachineNumber, false);
            if (AxCzkem1.ReadGeneralLogData(_iMachineNumber))
            {
                string sdwEnrollNumber;
                int idwVerifyMode;
                int idwInOutMode;
                int idwYear;
                int idwMonth;
                int idwDay;
                int idwHour;
                int idwMinute;
                int idwSecond;
                int idwWorkcode = 0;

                while (AxCzkem1.SSR_GetGeneralLogData(_iMachineNumber, out sdwEnrollNumber, out idwVerifyMode,
                    out idwInOutMode, out idwYear, out idwMonth, out idwDay, out idwHour, out idwMinute, out idwSecond,
                    ref idwWorkcode)) //get records from the memory
                {
                    DataRow row = table.NewRow();
                    row["IDMachineKeeper"] = _iMachineNumber.ToString(CultureInfo.InvariantCulture);
                    row["EnrollNumber"] = sdwEnrollNumber;
                    row["VerifyMode"] = idwVerifyMode.ToString(CultureInfo.InvariantCulture);
                    row["InOutMode"] = idwInOutMode.ToString(CultureInfo.InvariantCulture);
                    row["Date"] = idwYear + "-" + idwMonth + "-" + idwDay + " " + idwHour + ":" + idwMinute + ":00";
                    row["Workcode"] = idwWorkcode.ToString(CultureInfo.InvariantCulture);
                    table.Rows.Add(row);
                }
            }
            return table;
        }

        protected void btnDowloadAttLogs_OnClick(object sender, DirectEventArgs e)
        {
            var max = new DateTime();
            var check = Mck.GetMaxDate_MCK();
            if (check != null && check.Rows.Count > 0)
            {
                max = DateTime.Parse(check.Rows[0]["MCK_Date"].ToString());
            }
            var dt = getDataCheckLog();
            foreach (DataRow row in dt.Rows)
            {
                if (DateTime.Parse(row["Date"].ToString()) > max)
                {
                    var new_mck = new MCK_ET
                    {
                        MCK_EnrollNumber = row["EnrollNumber"].ToString(),
                        MCK_Date = DateTime.Parse(row["Date"].ToString())
                    };
                    MCK_BLL.Insert_MCK(new_mck);
                }
            }
            StoreMCK.DataSource = Mck.GetData_MCK(string.Empty);
            StoreMCK.DataBind();
        }
    }
}